package examples.game;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

/**
 * @author Orlin Tomov
 *
 */
public class BullsAndCows {

	public static final int NUM_DIGITS = 4;

	private Digits secret;
	private Map<Digits,Match> play;

	public BullsAndCows() {
		init();
	}

	/**
	 * Inits {@link #secret}
	 */
	public void init() {
		secret = new Digits();
		play = new LinkedHashMap<Digits,Match>();
	}

	/**
	 * 
	 * @return next move
	 */
	public Digits nextMove() {
		Digits digits = new Digits();
		if (play.size() > 0) {
			boolean searching = true;
			while (searching) {
				for (Entry<Digits,Match> entry: play.entrySet()) {
					Digits move = entry.getKey();
					Match answer = entry.getValue();
					if (digits.equals(move)) {
						/** there was move like this already */
						digits = new Digits(digits);
						searching = true;
						break;
					}
					Match match = new Match(move, digits);
					if (!match.equals(answer)) {
						/** bad move */
						digits = new Digits(digits);
						searching = true;
						break;
					} else {
						searching = false;
					}
				}
			}
		}
		play.put(digits, null);
		return digits; 
	}

	public Match getAnswer(Digits move) {
		Match answer = new Match(secret, move);
		return answer;
	}

	public Digits setAnswer(Match answer) {
		Digits move = null;
		Iterator<Digits> i = play.keySet().iterator();
		while(i.hasNext()) {
			move = i.next();
		}
		play.put(move, answer);
		return move;
	}

	public static void main(String[] args) {
		BullsAndCows game = new BullsAndCows();
		System.out.println("secret: " + game.secret);
		while(true) {
			Digits move = game.nextMove();
			Match answer = game.getAnswer(move);
			game.setAnswer(answer);
			System.out.println("guess: " +  move + " - " + answer);
			if (answer.getBulls() == NUM_DIGITS) {
				break;
			}
		}
	}
}
